const fs = require('fs');
const path = require('path');
const { fileURLToPath } = require('url');

let home = 'applet\\pages'

var pages_dir = path.resolve(__dirname, './pages');

let is_run;
fs.watch(pages_dir, {recursive: true}, (eventType, filename) => {
	if(is_run)clearTimeout(is_run);
	is_run = setTimeout(()=>{
		auto_router()
	},100)
});

auto_router()

var pages_str = null;
function auto_router(){

	let vue_buts = {};
	
	let dirs = (dirPath)=>{
		const files = fs.readdirSync(dirPath);

		files.forEach(file => {
			const fullPath = path.join(dirPath, file);
			const stats = fs.statSync(fullPath);
			if (stats.isDirectory()) {
				dirs(fullPath);
			} else {
				let extname = path.extname(fullPath).toLowerCase();
				let path_dir = dirPath.replaceAll(pages_dir+'\\','').replaceAll('\\','/');
				let path_file = fullPath.replaceAll(pages_dir+'\\','').replaceAll('\\','/');
				
				if(extname == '.php' && /^[\da-zA-Z_\-\/]+$/.test(path_file.substr(0,path_file.length-4))){
					
					let file_data = fs.readFileSync(fullPath, 'utf8');

					let name_arr = path_file.split('/');
					name_arr.unshift(home);
					name_arr.pop();

					if(name_arr.length){
						let new_name = name_arr.join('\\');

						let str = file_data.match(/\snamespace\s(\S+);/)
						if(str){
							if(str[1] != new_name){
								console.log(path_file)

								let save = file_data.replace(/(\snamespace\s)\S+;/,'$1' + name_arr.join('\\') + ';');

								fs.writeFileSync(fullPath, save, 'utf8');
							}
						}

					}
				}
			}
		});
	}

	dirs(pages_dir);
}